import { MutableRefObject } from 'react';
import { extendApi } from '@inbiz/utils';
import type { IProps } from './index';

export default extendApi((_events: MutableRefObject<IProps['callBackEvents']>, props: IProps) => {
  return {
    getText: () => {
      return props.value.map((item: any) => item.name).join(',');
    },
    getSaveData: () => {
      if (props.mode === 'SelectFile') {
        return {
          value: props.value?.map((item: any) => item.fileid).join(','),
          childData:
            props.storageConfig && props.childModelConfig
              ? {
                  controlId: props.controlId,
                  modelKey: props.storageConfig?.business,
                  datas: [
                    ...(props.value ?? []).map((item: any) => {
                      return props.storageConfig?.tableData.reduce((pre: any, next: any) => {
                        pre[next.modelAttr] = item[next.componentAttr];
                        pre['_opt'] = 'add';
                        return pre;
                      }, {});
                    }),
                    {
                      _opt: 'del',
                    },
                  ],
                }
              : undefined,
        };
      } else {
        return {
          value: props.value?.map((item: any) => item.folderid).join(','),
          childData:
            props.storageConfig && props.childModelConfig
              ? {
                  controlId: props.controlId,
                  modelKey: props.storageConfig?.business,
                  datas: [
                    ...(props.value ?? []).map((item: any) => {
                      return props.storageConfig?.tableData.reduce((pre: any, next: any) => {
                        pre[next.modelAttr] = item[next.componentAttr];
                        pre['_opt'] = 'add';
                        return pre;
                      }, {});
                    }),
                    {
                      _opt: 'del',
                    },
                  ],
                }
              : undefined,
        };
      }
    },
  };
});
